# -*-coding:utf-8-*-
# 2024年1月19日 星期五
# pdf 合并工具柜
import os.path
import sys

import uymas
from uymas import lists
import uymas.zy.uymas as uy
from pypdf import PdfWriter, PdfReader

import cmd_img2pdf
import common


def cmd_help():
    print("基于 pypdf 实现PDF文档合并/分割等")
    print("参考文档  https://github.com/py-pdf/pypdf ")
    print("参考文档  https://pypdf.readthedocs.io/en/latest ")
    print()
    print("Example:")
    print("pdf 合并")
    print("$ -o merge.pdf input1.pdf input2.pdf input3.pdf input4.pdf")
    print("$ input1.pdf input2.pdf input3.pdf input4.pdf")
    print("-o 或 --output 不指定时默认为 merge.pdf")
    print()
    print("split   pdf 分割")
    print("$ split data.pdf")
    print()
    print("stat    pdf 详细信息获取")
    print("$ stat data.pdf")
    print()
    print("img2pdf [path]   给定图片路径合并为pdf，别名 i2p")
    print("$ img2pdf /path/img_lists")
    print()
    print("版本：{}/{}".format(common.__version__, common.__release__))
    print()


def cmd_merge(sys_args: list[str]):
    """
    文件合并
    :return:
    """
    # 文档参数解析
    output = "merge.pdf"
    file_list = []
    last_cmd = ""
    for arg in sys_args:
        if last_cmd == "-o" or last_cmd == "--output":
            output = arg
            last_cmd = arg
            continue

        try:
            if arg.index(".pdf") > 0:
                file_list.append(arg)
        except Exception as e:
            pass

        last_cmd = arg

    if len(file_list) < 1:
        print("错误：您没有输入任何需要合并的文件")
        sys.exit()

    print()
    print("正在将 {} \n    合并为 {}，请稍后……".format(",".join(file_list), output))
    print()

    # 尝试进行合并
    spend_time = uymas.get_time_spend()
    try:
        merger = PdfWriter()
        for pdf in file_list:
            merger.append(pdf)

        merger.write(output)
        merger.close()

        print("pdf文件合并成功！")
        print(f"  {output}")

    except Exception as e:
        print("PDF 合并错误，参考信息：")
        print(f"  {e}")

    print(f"用时 {spend_time()} 秒")


def cmd_split(opt: uy.Option):
    """
    pdf 分割
    :param sys_args:
    :return:
    """
    spend_time = uymas.get_time_spend()
    py_path = opt.action
    py_name_tuple = os.path.splitext(os.path.basename(py_path))

    if not py_path:
        print("请先指定 pdf 文件")
        return

    try:
        reader = PdfReader(py_path)
    except Exception as e:
        print(f"{py_path} 读取错误，{e}")
        return

    print("共获取得页数：{}".format(len(reader.pages)))
    count = 0
    for number, page in enumerate(reader.pages):
        writer = PdfWriter()
        writer.add_page(page)

        # Write to pypdf-output.pdf.
        with open(f"output/{py_name_tuple[0]}-p{number + 1}.pdf", "wb") as fp:
            writer.write(fp)
            count += 1

    # 获取附件
    for name, content_list in reader.attachments.items():
        for i, content in enumerate(content_list):
            with open(f"{name}-{i}", "wb") as fp:
                fp.write(content)

    print(f"成功split文件数：{count}")
    print(f"用时 {spend_time()} 秒")


def cmd_stat(sys_args: list[str]):
    """
    pdf 详情
    :param sys_args:
    :return:
    """
    get_arg_fn = lists.get_list_index(sys_args)
    py_path = get_arg_fn(2)

    if not py_path:
        print("请先指定 pdf 文件")
        return

    try:
        reader = PdfReader(py_path)
    except Exception as e:
        print(f"{py_path} 读取错误，{e}")
        return

    meta = reader.metadata
    print("读取文件成功")
    print("页数：{}".format(len(reader.pages)))
    print()
    print("meta info")
    print("tile：{}".format(meta.title))
    print("author：{}".format(meta.author))
    print("subject：{}".format(meta.subject))
    print("creator：{}".format(meta.creator))
    print("producer：{}".format(meta.producer))
    print("creation_date：{}".format(meta.creation_date))
    print("modification_date：{}".format(meta.modification_date))
    print()


if __name__ == "__main__":
    option = uy.Option()

    sys_args = sys.argv[1:]
    if len(sys_args) == 0:
        cmd_help()
        sys.exit()

    # 命令路由
    match option.command:
        # pdf 分割
        case "split":
            cmd_split(option)
        # pdf 详情查看
        case "stat":
            cmd_stat(sys_args)
        # 帮助信息输出
        case "help":
            cmd_help()
        case "img2pdf" | "i2p":
            cmd_img2pdf.action_command(option)
        case _:
            cmd_merge(sys_args)
